import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BusinessGalleryEntity } from '../entity/gallery';
import { BusinessProductAListEntity } from '../entity/product/a_list';
import { BusinessProductBListEntity } from '../entity/product/b_list';
import * as _ from 'lodash';
import { CacheManager } from '@midwayjs/cache';
import { Context } from '@midwayjs/koa';

/**
 * 图库
 */
@Provide()
export class BusinessGalleryService extends BaseService {
  @InjectEntityModel(BusinessGalleryEntity)
  businessGalleryEntity: Repository<BusinessGalleryEntity>;

  @InjectEntityModel(BusinessProductAListEntity)
  businessProductAListEntity: Repository<BusinessProductAListEntity>;

  @InjectEntityModel(BusinessProductBListEntity)
  businessProductBListEntity: Repository<BusinessProductBListEntity>;

  @Inject()
  cacheManager: CacheManager;

  @Inject()
  ctx: Context;

  /**
   * 新增
   * @param param
   */
  async addItem(param) {
    const { userId } = this.ctx.admin;
    const code = param.code
    const mainImage = param.mainImage
    const additionalImages = param.additionalImages
    const remark = param.remark
    const productType = this.getProductTypeByCode(code)
    // 获取产品实例
    let product = undefined
    if (productType === '1') {
      product = await this.businessProductAListEntity.findOneBy({
        userId: userId,
        code: code,
      });
    }
    if (productType === '2') {
      product = await this.businessProductBListEntity.findOneBy({
        userId: userId,
        code: code,
      });
    }
    // 判定产品是否存在
    if (!product) {
      throw new CoolCommException('产品不存在');
    }
    // 判定产品是否已绑定图库
    if (product.galleryId) {
      throw new CoolCommException('产品已绑定图库,无法继续新增绑定');
    }
    // 新增图库
    const gallery = await this.businessGalleryEntity.save({
      userId: userId,
      productNo: code,
      mainImage: mainImage,
      additionalImages: additionalImages,
      remark: remark
    });
    // 更新产品galleryId
    product.galleryId = gallery.id
    await product.save()
    return gallery
  }

  /**
 * 获取分页数据（用户端）
 */
  async getPageByUser(query: any) {
    const { userId } = this.ctx.admin;
    const option = {
      keyWordLikeFields: ['productNo'],
      where: async (ctx: Context) => {
        const res = []
        if (query.date) {
          const date_query = ["createTime > :date_start AND createTime < :date_end", { date_start: `${query.date} 00:00:00`, date_end: `${query.date} 23:59:59` }]
          res.push(date_query)
        }
        return res
      }
    }
    query.userId = userId;
    return await super.page(query, option);
  }

  // 获取详细信息
  async getInfoByUser(id) {
    const { userId } = this.ctx.admin;
    const gallery = await this.businessGalleryEntity.findOneBy({ userId, id });
    return gallery
  }

  // 更新数据
  async updateByUser(data) {
    const { userId } = this.ctx.admin;
    const id = data.id
    delete data.productNo
    const gallery = await this.businessGalleryEntity.findOneBy({ userId, id });
    if (gallery) {
      return await this.businessGalleryEntity.save(data)
    } else {
      throw new CoolCommException('数据不存在');
    }
  }

  // 根据产品编码获取产品类型
  getProductTypeByCode(code: string) {
    return code.match(/P(\S*)B/)[1];
  }
}
